package com.cplatform.movie.back.sys.web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cplatform.dbhelp.page.Page;
import com.cplatform.movie.back.model.SessionUser;
import com.cplatform.movie.back.sys.dao.SysFilterWordDao;
import com.cplatform.movie.back.sys.dao.SysUnitDao;
import com.cplatform.movie.back.sys.entity.SysFilterWord;
import com.cplatform.movie.back.sys.service.SysInfoService;
import com.cplatform.movie.back.utils.AppConfig;
import com.cplatform.movie.back.utils.JsonRespWrapper;
import com.cplatform.movie.back.utils.LogUtils;
import com.cplatform.util2.TimeStamp;

/**
 * Title.过滤字管理 <br>
 * Description.
 * <p>
 * Copyright: Copyright (c) 2013-5-23 下午5:41:46
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: baibo@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */

@Controller
@RequestMapping("/sys/filterword")
public class FilterWordController {

	
	private static final Logger log = Logger.getLogger(FilterWordController.class);
	@Autowired
	SysUnitDao unitDao;

	@Autowired
	SysFilterWordDao filterDao;

	@Autowired
	SysInfoService filterService;
	
	@Autowired
	private LogUtils logUtils;
	

	@Autowired
	private AppConfig appConfig;

	@RequestMapping(value = "list")
	public String queryFilterWordList(SysFilterWord filterWord, @RequestParam(value = "page", required = false, defaultValue = "1") int page,
	        HttpSession session, Model model) throws SQLException {
		Page<SysFilterWord> filterlist = filterService.findFilterWord(filterWord, page);
		model.addAttribute("pageData", filterlist);
		return "sys/filterword/filter_word_list";
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String toAdd(Model model) throws SQLException {
		SysFilterWord filterWord = new SysFilterWord();
		model.addAttribute("filterWord", filterWord);
		return "sys/filterword/filter_word_add";
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Object add(@ModelAttribute("filterWord") SysFilterWord developer, HttpServletRequest request, BindingResult result) throws SQLException {
		try {
			SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			String unitId = sessionUser.getUnitId().toString();
			// 判断是否重复
			if (filterDao.checkFilterWord(developer.getWord(), unitId) == 0) {
				developer.setUnitId(unitId);
				developer.setInTag(Short.valueOf("0"));
				developer.setUpdateTime(TimeStamp.getTime(14));
				developer.setUpdateUserId(sessionUser.getId());
				logUtils.logAdd("过滤字管理", "添加过滤字，过滤字编号：" +developer.getId());
				filterDao.save(developer);
				return JsonRespWrapper.success("操作成功", "/sys/filterword/list");
			} else {
				return JsonRespWrapper.success("过滤字已经存在！", "/sys/filterword/list");
			}
		}
		catch (Exception ex) {
			// 未知的错误消息，一般是exception catch后通知用户
			log.error(ex.getMessage());
			return JsonRespWrapper.error(ex.getMessage());
		}
	}

	@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
	public String toEdit(@PathVariable Long id, Model model) throws SQLException {

		SysFilterWord filterWord = filterDao.findOne(id);
		model.addAttribute("filterWord", filterWord);
		return "sys/filterword/filter_word_edit";
	}

	@RequestMapping(value = "edit/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Object edit(@ModelAttribute("filterWord") SysFilterWord developer, HttpServletRequest request, BindingResult result) throws SQLException {
		try {
			SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			String unitId = sessionUser.getUnitId().toString();
			// 判断是否重复
			if (filterDao.checkFilterWord(developer.getWord(), unitId) == 0) {
				developer.setUpdateTime(TimeStamp.getTime(14));
				developer.setUnitId(unitId);
				developer.setInTag(Short.valueOf("0"));
				developer.setUpdateUserId(sessionUser.getId());
				filterDao.save(developer);
			     logUtils.logOther("过滤字管理", "过滤字编号："+developer.getId());
				return JsonRespWrapper.success("操作成功", "/sys/filterword/list");
			} else {
				return JsonRespWrapper.success("过滤字已经存在！", "/sys/filterword/list");
			}
		}
		
		catch (Exception ex) {
			// 未知的错误消息，一般是exception catch后通知用户
           logUtils.logOther("过滤字管理", "过滤字编号："+developer.getId());
			log.error(ex.getMessage());
			return JsonRespWrapper.error(ex.getMessage());
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public Object del(@PathVariable Long id) throws SQLException {
		try {
			logUtils.logDelete("过滤字管理", "添加过滤字，过滤字编号：" +id);
			filterDao.delete(id);
			return JsonRespWrapper.success("操作成功", "/sys/filterword/list");
		}
		catch (Exception ex) {
			// 未知的错误消息，一般是exception catch后通知用户
			logUtils.logDelete("过滤字管理", "添加过滤字失败，过滤字编号：" +id);
			log.error(ex.getMessage());
			return JsonRespWrapper.error(ex.getMessage());
		}
	}

	@RequestMapping(value = "batchadd", method = RequestMethod.GET)
	public String toBatchAddPage(Model model) throws SQLException {
		SysFilterWord filterWord = new SysFilterWord();
		model.addAttribute("filterWord", filterWord);
		return "sys/filterword/filter_word_batchadd";
	}

	@RequestMapping(value = "batchadd", method = RequestMethod.POST)
	@ResponseBody
	public Object batchAdd(@RequestParam("batchFile") MultipartFile batchFile, HttpSession session) throws SQLException {
		try {
			if (batchFile == null) {
				// 提示用户必须要上传文件
				return JsonRespWrapper.success("您选择要导入的文件。", "/sys/filterword/list");
			}
			SessionUser sessionUser = (SessionUser) session.getAttribute(SessionUser.SESSION_USER_KEY);
			Long userId = sessionUser.getId();
			String unitId = sessionUser.getUnitId().toString();
			String time = TimeStamp.getTime(14);
			// 处理上传的文件
			BufferedReader br = new BufferedReader(new InputStreamReader(batchFile.getInputStream(), "GBK"));
			String word = null;
			int counter = 0;
			int reCounter = 0;
			String lenght = "";
			int i = 0;
			while ((word = br.readLine()) != null) {
				if (!"".equals(word)) {
					i++;
					if (word.length() > 25) {
						lenght = lenght + i + "、";
						continue;
					}
					if (filterDao.checkFilterWord(word, unitId) == 0) {
						SysFilterWord filterWord = new SysFilterWord();

						filterWord.setWord(word);
						filterWord.setInTag(Short.valueOf("1"));
						filterWord.setUnitId(unitId);
						filterWord.setUpdateTime(time);
						filterWord.setUpdateUserId(userId);
						filterDao.save(filterWord);
						counter++;
					} else {
						reCounter++;
					}
				}
			}
			String suc = "导入成功" + counter + "条。重复" + reCounter + "条。";
			if (!"".equals(lenght)) {
				suc = suc + "第" + lenght.substring(0, lenght.lastIndexOf("、")) + "行过长，长度不超过25个汉字。";
			}
			logUtils.logOther("过滤字管理", "过滤字导出，过滤字编号：" );

			return JsonRespWrapper.success(suc, "/sys/filterword/list");
			
		}
		catch (Exception ex) {
			logUtils.logOther("过滤字管理", "过滤字导出失败，过滤字编号：" );
			// 未知的错误消息，一般是exception catch后通知用户
			log.error(ex.getMessage());
			return JsonRespWrapper.error(ex.getMessage());
		}
	}

}
